

<div class="layuimini-container layuimini-page-anim">
  <div class="layuimini-main">

    <div id="test2" class="demo-transfer"></div>

    <button class="layui-btn layui-btn-warm template-download" style="border-radius:6px;background-color:#26B99A;"
      lay-demotransferactive="getData">生成样式</button>
    <button class="layui-btn layui-btn template-download" style="border-radius:6px;background-color:#26B99A;"
      lay-demotransferactive="reload">清空样式</button>

    <button class="layui-btn layui-btn template-download save"
      style="border-radius:6px;background-color:#26B99A;">保存</button>
    <!-- layui.table.cache["test"] -->
  </div>

  <div class="layuimini-main">
    <form action="" lay-filter="example">
      <table class="layui-hide" id="test"></table>
    </form>

  </div>
</div>


<script type="text/html" id="selectTpl">
        <select name="interest" lay-filter="aihao">
          <option {{ d.fieldType == "1" ? 'selected' : '' }} value="1" >文本框</option>
          <!-- <option {{ d.fieldType == "2" ? 'selected' : '' }} value="2">下拉列表</option> -->
          <!-- <option {{ d.fieldType == "3" ? 'selected' : '' }} value="3">单选按钮</option> -->
          <!-- <option {{ d.fieldType == "4" ? 'selected' : '' }} value="4">复选框</option> -->
          <option {{ d.fieldType == "5" ? 'selected' : '' }} value="5">时间框</option>
          <option {{ d.fieldType == "6" ? 'selected' : '' }} value="6">邮箱</option>
          <!-- <option {{ d.fieldType == "7" ? 'selected' : '' }} value="7">导航</option> -->
          <option {{ d.fieldType == "8" ? 'selected' : '' }} value="8">关键词</option>
          <option {{ d.fieldType == "10" ? 'selected' : '' }} value="10">全文框</option>
        </select>
</script>

<script type="text/html" id="isNotNullTpl">
  <input type="checkbox" name="" lay-skin="primary" {{ d.isAllowNull == "1" ? 'checked' : '' }}>
</script>

<script type="text/html" id="isUniqueTpl">
  <input type="checkbox" name="" lay-skin="primary" {{ d.isOnlyOne == "1" ? 'checked' : '' }}>
</script>

<script>


  var rowData;

  var dbCode;
  var dbName;

  var canSave = true

  //处理父级页面数据
  if (data_userMgr) {
    getDataBaseConfInfo(data_userMgr)
  } else {
    alert(0)
  }
  function getDataBaseConfInfo(data_userMgr) {
    dbCode = data_userMgr.databasecode
    dbName = data_userMgr.databasename
    var DBcode = data_userMgr.databasecode
    renderTrans([])
    shared.ajaxGet('/DIYTag/getNotSysFieldsState', { "DBcode": DBcode }, function (res) {
      if (res) {
        rowData = res
        renderTrans(res)
      }
    })
  }

  //从ajax获取字段数据,渲染穿梭框(同时渲染表格)
  function renderTrans(data) {
    dataList = []
    selectedList = []
    customerFieldData = []
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      dataList.push({ "value": element.field, "title": element.field })
      if (element.isPublish) {
        selectedList.push(element.field)
        customerFieldData.push(
          {
            "field": element.field,
            "fieldDisplaydName": element.fieldDisplaydName,
            "defaultValue": element.defaultValue,
            "descript": element.descript
            , "fieldType": element.fieldType
            , "isAllowNull": element.isAllowNull
            , "isOnlyOne": element.isOnlyOne
          }
        )
      }
    }
    layui.use(['transfer'], function () {
      var transfer = layui.transfer
      transfer.render({
        elem: '#test2'
        , title: ['可提交字段', '选择的提交字段']  //自定义标题
        , data: dataList
        , value: selectedList
        , width: 150 //定义宽度
        , height: 400 //定义高度
        , id: "key123"
      })
    })

    /*
    开始渲染表格
    */
    renderTable(customerFieldData)
  }


  function Completion(data) {

    theShowEles = document.getElementsByClassName('layui-select-title')
    for (let index = 0; index < theShowEles.length; index++) {
      const element = theShowEles[index];
      var theShowElesNext = element.nextElementSibling
      for (let _ = 0; _ < theShowElesNext.children.length; _++) {
        const child = theShowElesNext.children[_];
        if (child.getAttribute('class') == 'layui-this') {
          data['fields'][index]["fieldType"] = child.getAttribute('lay-value')
          break
        }
      }
    }

    theNotNullTds = $('td[data-field="isNotNull"]')
    for (let index = 0; index < theNotNullTds.length; index++) {
      const element = theNotNullTds[index];
      if (element.children[0].children[1].getAttribute('class') == "layui-unselect layui-form-checkbox layui-form-checked") {
        data['fields'][index]["isAllowNull"] = 1
      } else {
        data['fields'][index]["isAllowNull"] = 0
      }
    }

    theNotNullTds = $('td[data-field="isUnique"]')
    for (let index = 0; index < theNotNullTds.length; index++) {
      const element = theNotNullTds[index];
      if (element.children[0].children[1].getAttribute('class') == "layui-unselect layui-form-checkbox layui-form-checked") {
        data['fields'][index]["isOnlyOne"] = 1
      } else {
        data['fields'][index]["isOnlyOne"] = 0
      }
    }
  }

  //点击保存按钮
  $(".save").click(function () {
    if(!canSave){
      layer.msg("保存前需要生成样式", {
          icon: 0,
          time: 2000 //2秒关闭（如果不配置，默认是3秒）
        })
      return;
    }

    //能到这里,一定是有非系统字段的,就取第一个作为dbcode
    var data = {}
    data["dbCode"] = dbCode
    data["dbName"] = dbName
    data["fields"] = []

    var tableRes = layui.table.cache["test"]
    for (let index = 0; index < tableRes.length; index++) {
      const element = tableRes[index];
      var obj = {}
      obj["field"] = element["field"]
      obj["fieldDisplaydName"] = element["fieldDisplaydName"]
      // obj["fieldType"] = element["fieldType"]
      obj["defaultValue"] = element["defaultValue"]
      // obj["isAllowNull"] = element["isAllowNull"]
      // obj["isOnlyOne"] = element["isOnlyOne"]
      obj["descript"] = element["descript"]
      data["fields"].push(obj)
    }
    Completion(data)


    shared.ajaxPost('/DIYTag/save', data, function (res) {
      if (res == true) {
        layer.msg("保存成功", {
          icon: 1,
          time: 1000 //2秒关闭（如果不配置，默认是3秒）
        }, function () {
          layer.closeAll();
        });
      }

    })
  })


  //渲染table
  function renderTable(data) {


    layui.use(['table'], function () {
      var table = layui.table;

      table.render({
        elem: '#test'
        , data: data
        // , cellMinWidth: 80
        // , page: false
        , limit: Number.MAX_VALUE
        , cols: [[
          { type: 'numbers' }
          , { field: 'field', title: '字段', width: '15%' }
          , { field: 'fieldDisplaydName', edit: 'text', title: '显示名', width: '20%' }
          , { field: 'fieldType', title: '类型', templet: '#selectTpl', width: '10%' }
          , { field: 'defaultValue', title: '默认值', edit: 'text', width: '15%' }
          , { field: 'isNotNull', title: '非空', templet: '#isNotNullTpl', width: '8%' }
          , { field: 'isUnique', title: '唯一', templet: '#isUniqueTpl', width: '8%' }
          , { field: 'descript', title: '描述', edit: 'text', width: '20%' }
        ]]
        , done: function (res, curr, count) {
          //表格下拉自适应
          layui.each($('select'), function (index, item) {
            var elem = $(item);
            elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
          });
        }
      })
    })
  }




  //监听清空样式和生成样式
  layui.use(['util', 'transfer', 'table'], function () {

    var util = layui.util,
      table = layui.table,
      transfer = layui.transfer;

    util.event('lay-demoTransferActive', {
      getData: function (othis) {
        var getData = transfer.getData('key123'); //获取右侧数据
        dataInTable = table.cache["test"]

        GG = []
        for (let index = 0; index < getData.length; index++) {
          const element = getData[index];
          aa = element.value
          exist = false
          for (let index_ = 0; index_ < dataInTable.length; index_++) {
            const element_ = dataInTable[index_];
            bb = element_.field
            if (aa == bb) {
              GG.push({
                "field": element_.field,
                "fieldDisplaydName": element_.fieldDisplaydName,
                "defaultValue": element_.defaultValue,
                "descript": element_.descript
                , "fieldType": element_.fieldType
                , "isAllowNull": element_.isAllowNull
                , "isOnlyOne": element_.isOnlyOne
              })
              exist = true
              break
            }
          }
          if (!exist) {
            GG.push(
              {
                "field": element.value,
                "fieldDisplaydName": element.title,
                "defaultValue": "",
                "descript": ""
                , "fieldType": 1
                , "isAllowNull": 0
                , "isOnlyOne": 0
              }
            )
          }
        }
        renderTable(GG)
        canSave = true
      }
      , reload: function () {
        canSave = false
        //实例重载
        transfer.reload('key123', {
          value: []
        })
      }
    });
  })
</script>